package com.smile.frame.springbootsatoken.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * token拦截
 *
 * @author LGC
 */
@Slf4j
@Component
@Order(2)
public class TokenTraceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("token拦截");
        String token = request.getHeader(TokenConstants.AUTHORIZATION_KEY);
        if (token != null) {
            TokenContext.setCurrentToken(token);
        }
        log.info("Put token {} to context", token);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String token = request.getHeader(SecurityConstants.AUTHORIZATION_KEY);
        if (token != null) {
            TokenContext.clear();
        }
        log.info("Clear token {} to context", token);
    }
}